package com.lin.missyou.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.type.TypeReference;
import com.lin.missyou.core.enumeration.OrderStatus;
import com.lin.missyou.dto.OrderAddressDTO;
import com.lin.missyou.util.CommonUtil;
import com.lin.missyou.util.GenericAndJson;
import lombok.*;
import org.hibernate.annotations.Where;

import javax.persistence.*;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author gcq
 * @Create 2021-11-08
 */
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Where(clause = "delete_time is null")
@Table(name = "`Order`")
public class Order extends BaseEntity{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String orderNo;
    private Long userId;
    private BigDecimal totalPrice;
    private Long totalCount;
    private String snapImg;
    private String snapTitle;
    private String snapItems;
    private String snapAddress;
    private String prepayId;
    private BigDecimal finalTotalPrice;
    /**
     * 订单状态
     */
    private Integer status;
    /**
     * 下单时间
     */
    private Date placedTime;
    /**
     * 订单过期时间
     */
    private Date expiredTime;

    /**
     * 转换
     * @return
     */
    @JsonIgnore
    public OrderStatus getStatusEnum() {
        return OrderStatus.toType(this.status);
    }

    /**
     * 订单是否过期
     * @return
     */
    public boolean needCancel() {
        // 订单状态判断
        if (!this.getStatusEnum().equals(OrderStatus.UNPAID)) {
            return true;
        }
        // 订单过期时间判断
        return CommonUtil.isOutOfDate(this.expiredTime);
    }

    public List<OrderSku> getSnapItems() {
        if (this.snapItems == null) {
            return Collections.emptyList();
        }
        return GenericAndJson.jsonToObject(this.snapItems, new TypeReference<List<OrderSku>>() {
        });
    }

    public void setSnapItems(List<OrderSku> orderSkus) {
        if (orderSkus == null) {
            return;
        }
        this.snapItems = GenericAndJson.objectToJson(orderSkus);
    }

    public OrderAddressDTO getSnapAddress() {
        if (this.snapAddress == null) {
            return null;
        }
        return GenericAndJson.jsonToObject(this.snapAddress, new TypeReference<OrderAddressDTO>() {
        });
    }

    public void setSnapAddress(OrderAddressDTO snapAddress) {
        if (snapAddress == null) {
            return;
        }
        this.snapAddress = GenericAndJson.objectToJson(snapAddress);
    }
}